package base.thread.waitNotify;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SignalAndAwaitDemo {

    private int i=0;

//    private Object obj=new Object();

    private Lock lock=new ReentrantLock(false);
    private Condition condition=lock.newCondition();


    private void odd()  {

        while (i<10){
            lock.lock();
                if (i%2==1){
                    System.out.println("奇数  "+i);
                    i++;
                    condition.signal();
                }else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
        }

    }

     private void even() {
            while (i<10){
                lock.lock();
                if (i%2==0){
                    System.out.println("偶数  "+i);
                    i++;
                    condition.signal();
                }else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
    }


    public static void main(String[] args) {
        SignalAndAwaitDemo demo=new SignalAndAwaitDemo();

        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                    demo.odd();
            }
        });

         Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                    demo.even();

            }
        });

        thread1.start();
        thread2.start();
    }























}
